package com.hunlian.makelove.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.BaseFragemt;
import com.hunlian.makelove.R;
import com.hunlian.makelove.activity.MainActivity;
import com.hunlian.makelove.activity.SettingActivity;
import com.hunlian.makelove.activity.SpaceImageDetailActivity;
import com.hunlian.makelove.bean.UserBean2;
import com.hunlian.makelove.bean.UserIdAndCompleteBean;
import com.hunlian.makelove.clipimage.ClipImageActivity;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.ContextUtils;
import com.hunlian.makelove.common.Printout;
import com.hunlian.makelove.common.StringUtil;
import com.hunlian.makelove.dialog.HeightSelectorDialog;
import com.hunlian.makelove.net.HttpPostUploadUtil;
import com.hunlian.makelove.net.IServiceReturnProcess;
import com.hunlian.makelove.net.NetVisitCallback;
import com.hunlian.makelove.net.ServiceInterfaceDef;
import com.hunlian.makelove.net.api.MineServiceVisit;
import com.hunlian.makelove.tools.DeviceTools;
import com.hunlian.makelove.tools.MyToast;
import com.hunlian.makelove.util.LogUtil;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

import static android.app.Activity.RESULT_OK;

public class MineFrag extends BaseFragemt {
    private MainActivity mActivity;
    private View contentView;
    private Button mBtnHobbyModify, mBtnIntroduceModify, mBtnExpectModify;
    private ImageButton mIvPhotoModify, mIbHeightModify;
    private com.facebook.drawee.view.SimpleDraweeView mIvPhoto;
    private UserBean2 mUserBean2;
    private Button mSave;
    private EditText mEtSex, mEtHobby, mEtIntroduce, mEtExpect;
    private TextView mTvNickname, mTvId, mTvHeight;
    private RelativeLayout mRlHeight;
    private HeightSelectorDialog mHeightSelectorDialog;
    private String mPhotoDir;
    private String mstrHeadPath;
    private String StrHead = "head";
    private String HeadPath;
    private int RequestCodeHeadCropper = 10;
    private final int REQUEST_CODE_ASK_CAMERA = 8000;
    private final String TAG = MineFrag.class.getName();


    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case HeightSelectorDialog.VALUE:
                    String height = msg.getData().getString("height");
                    mTvHeight.setText(height);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(mEtSex.getText().toString())||TextUtils.isEmpty(mstrHeadPath)) {
            request();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (contentView == null) {
            mActivity = (MainActivity) this.getActivity();
            contentView = inflater.inflate(R.layout.frag_mine, null);
            ButterKnife.bind(this, contentView);
            initView();

            //初始化照片信息
            mPhotoDir = ContextUtils.getPicDirName(mActivity, "HLW_Pics/person");
            HeadPath = mPhotoDir+StrHead+".jpg";

        }
        ViewGroup parent = (ViewGroup) contentView.getParent();
        if (parent != null) {
            parent.removeView(contentView);
        }
        return contentView;
    }

    private void initView() {

        //title
        ImageButton mIbSetting = (ImageButton) contentView.findViewById(R.id.ib_setting);
        mIbSetting.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, SettingActivity.class);
                startActivity(intent);
            }
        });

        mIvPhotoModify = (ImageButton) contentView.findViewById(R.id.iv_photo_modify);
        mTvNickname = (TextView) contentView.findViewById(R.id.tv_nickname);
        mTvId = (TextView) contentView.findViewById(R.id.tv_id);
        mEtSex = (EditText) contentView.findViewById(R.id.et_sex);
        mTvHeight = (TextView) contentView.findViewById(R.id.tv_height_value);
        mRlHeight = (RelativeLayout) contentView.findViewById(R.id.rl_height);
        mIbHeightModify = (ImageButton) contentView.findViewById(R.id.btn_height_edit);
        mEtHobby = (EditText) contentView.findViewById(R.id.et_hobby);
        mBtnHobbyModify = (Button) contentView.findViewById(R.id.btn_hobby_edit);
        mEtIntroduce = (EditText) contentView.findViewById(R.id.et_introduce);
        mBtnIntroduceModify = (Button) contentView.findViewById(R.id.btn_introduce_edit);
        mEtExpect = (EditText) contentView.findViewById(R.id.et_expect);
        mBtnExpectModify = (Button) contentView.findViewById(R.id.btn_expect_edit);
        mSave = (Button) contentView.findViewById(R.id.btn_save);
        mSave.setClickable(false);
        mIvPhoto = (com.facebook.drawee.view.SimpleDraweeView) contentView.findViewById(R.id.iv_head);
        setOnClick();

        String model = DeviceTools.getDeviceModel();
        String os = DeviceTools.getDeviceOs();
        Log.e(TAG+" 设备型号: ",model);
        Log.e(TAG+" 设备系统: ",os);

    }

    private void setOnClick() {
        mIvPhotoModify.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                singleSelect();
            }

        });


        mRlHeight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mHeightSelectorDialog == null) {
                    mHeightSelectorDialog = new HeightSelectorDialog(mActivity,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, mHandler);
                }
                mHeightSelectorDialog.show();
            }
        });

        mSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                uploading();
            }

        });

        mIvPhoto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mActivity, SpaceImageDetailActivity.class);
                intent.putExtra("url",mstrHeadPath);
                startActivity(intent);
            }
        });

    }


    private void request() {
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            return;
        }
        createProgressDialog(mActivity);
        progressDialog.show();

        MineServiceVisit visit = new MineServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId());
        //System.out.println("我的请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<UserBean2, Object>(mActivity) {

            @Override
            public void onSuccess(UserBean2 data) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (data == null) return;
                mUserBean2 = data;
                //获得学历状态
                AppConfig.eduState = mUserBean2.getEduState();
                refreshView();
            }


            @Override
            public void onFailure(String errorEvent, String message, Object obja) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (ServiceInterfaceDef.SERVICE_RETURN_FAIL.equals(errorEvent)) {
                    try {
                        JSONObject obj = new JSONObject(message);
                        if (null == obj) {
                            Toast.makeText(mActivity, "请求失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String msg = obj.getString("message");
                        String beans = obj.getString("beans");
                        Gson gson = new Gson();
                        UserIdAndCompleteBean bean = gson.fromJson(beans, UserIdAndCompleteBean.class);
                        if ("false".equals(bean.getHasUserId())) {
                            Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                            //跳转到注册
                            skipToRegisterActivity(mActivity);
                        }
                        if ("false".equals(bean.getHasComplete())) {
                            Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                            //跳转到完善资料
                            skipToOrganizingDataActivity(mActivity);
                        }

                    } catch (Exception e) {
                        Toast.makeText(mActivity, "请求失败", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    super.onFailure(errorEvent, message, obja);
                }
            }

        });

    }

    private void refreshView() {

        if (mUserBean2 == null) return;
        if (mUserBean2.getPhoto() != null) {
            mIvPhoto.setImageURI(Uri.parse(mUserBean2.getPhoto()));
        }

        mTvNickname.setText(mUserBean2.getNickname());
        mEtSex.setText(mUserBean2.getSex());
        mTvHeight.setText(mUserBean2.getHeight());
        mEtHobby.setText(mUserBean2.getHobby());
        mEtIntroduce.setText(mUserBean2.getIntroduce());
        mEtExpect.setText(mUserBean2.getExpect());
        mTvId.setText(AppConfig.getInstance().getLoginedUserId());
        mSave.setClickable(true);
        mstrHeadPath = mUserBean2.getPhoto();
    }

    private void uploading() {
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("functionId", "HLW005");
        textMap.put("userId", AppConfig.getInstance().getLoginedUserId());
        textMap.put("nickname", mTvNickname.getText().toString());
        textMap.put("sex", mEtSex.getText().toString());

        String height = mTvHeight.getText().toString();
        if (StringUtil.isNotEmpty(height) == false) {
            Toast.makeText(mActivity, "请选择身高", Toast.LENGTH_SHORT).show();
            return;
        }
        textMap.put("height", mTvHeight.getText().toString());

        String hobby = mEtHobby.getText().toString();
        if (StringUtil.isNotEmpty(hobby) == false) {
            Toast.makeText(mActivity, "请填写兴趣爱好", Toast.LENGTH_SHORT).show();
            return;
        }
        textMap.put("hobby", mEtHobby.getText().toString());

        String introduce = mEtIntroduce.getText().toString();
        if (StringUtil.isNotEmpty(introduce) == false) {
            Toast.makeText(mActivity, "请填写补充介绍", Toast.LENGTH_SHORT).show();
            return;
        }
        textMap.put("introduce", mEtIntroduce.getText().toString());

        String expect = mEtExpect.getText().toString();
        if (StringUtil.isNotEmpty(expect) == false) {
            Toast.makeText(mActivity, "请填写期望对方", Toast.LENGTH_SHORT).show();
            return;
        }
        textMap.put("expect", mEtExpect.getText().toString());

        if (StringUtil.isNotEmpty(mstrHeadPath) == false) {
/*            Toast.makeText(mActivity, "请上传照片", Toast.LENGTH_SHORT).show();
            return;*/
        }
        Map<String, String> fileMap = new HashMap<String, String>();
        if (mstrHeadPath == null || mstrHeadPath.length() == 0) {
        } else {
            if(!mstrHeadPath.startsWith("http")) {
                fileMap.put("pic", mstrHeadPath);
            }
        }

        createProgressDialog(mActivity);
        progressDialog.show();

        HttpPostUploadUtil.doPost(ServiceInterfaceDef.SERVICE_URL, textMap, fileMap,
                new IServiceReturnProcess() {
                    @Override
                    public void process(String serviceReturn) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        Printout.println("我的保存反馈" + serviceReturn);

                        if (TextUtils.isEmpty(serviceReturn)) {
                            return;
                        }
                        try {
                            JSONObject obj = new JSONObject(serviceReturn);
                            String status = obj.getString("status");
                            if (status.equals("1")) {
                                Toast.makeText(mActivity, "保存成功", Toast.LENGTH_SHORT).show();
                                //成功后重新调用页面请求
                                request();

                            } else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                } else {
                    // Permission Denied
                    Toast.makeText(mActivity, "拍照授权被拒", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void startCropperActivity(int requestCode, String picPath,String savePath) {
        //编辑图片
        //Intent intent = new Intent(mSelf,CropperActivity.class);
        Intent intent = new Intent(mActivity, ClipImageActivity.class);
        intent.putExtra("path", picPath);
        intent.putExtra("savePath", savePath);
        startActivityForResult(intent, requestCode);
    }

    private static final int REQUEST_CODE = 111;
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    public void singleSelect() {
        ImgSelConfig config = new ImgSelConfig.Builder(mActivity,loader)
                // 是否多选
                .multiSelect(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                //.backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#3F51B5"))
                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机
                .needCamera(true)
                // 最大选择图片数量
                .maxNum(9)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if(data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

                mstrHeadPath = pathList.get(0);

                if (TextUtils.isEmpty(mstrHeadPath)) {
                    return;
                }
                //编辑图片
                startCropperActivity(RequestCodeHeadCropper, mstrHeadPath, HeadPath);
            }
        }else if(requestCode == RequestCodeHeadCropper && resultCode == RESULT_OK){
            mstrHeadPath = HeadPath;
            //加载并显示图片
            Fresco.getImagePipeline().evictFromCache(Uri.parse("file://"+mstrHeadPath));
            mIvPhoto.setImageURI(Uri.parse("file://"+mstrHeadPath));

        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.e("onDestroyView MF","onDestroyView MF");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.e("onDestroy MF","onDestroy MF");
    }
}
